/**
 * 
 */
package com.dangdang.service;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.dangdang.domain.CartItem;
import com.dangdang.domain.Item;
import com.dangdang.domain.Order;
import com.dangdang.domain.ReceiveAddress;
import com.dangdang.util.HbnUtils;

/**
 * 订单业务实现
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-29
 */
public class OrderServiceImpl implements OrderService {

	/**
	 * 创建订单
	 */
	public void createOrder(CartService cs, ReceiveAddress address) {
		Session session = HbnUtils.getSession();
		Transaction tx = session.beginTransaction();

		Order order = new Order();
		order.setUserId(cs.getUser().getId());
		order.setReceiveAddress(address);
		double totalPrice = 0.0;

		List<CartItem> cartItemList = cs.getCartItems();
		// 计算总价
		for (CartItem ct : cartItemList) {
			Item item = ct.toItem();
			order.addItem(item);
			totalPrice += item.getAmount();
		}

		// 订单状态
		order.setStatus(0);
		order.setOrderTime(new Date().getTime());
		order.setTotalPrice(totalPrice);
		order.setOrderDesc(".....");

		// 更新或保存地址
		address.setUserId(cs.getUser().getId());
		session.saveOrUpdate(address);

		session.save(order);

		tx.commit();
		session.close();

	}

	/**
	 * 根据ID删除订单
	 */
	public void deleteOrderById(Integer orderId) {
		Session session = HbnUtils.getSession();
		session.beginTransaction();
		try {
			Order order = (Order) session.get(Order.class, orderId);
			session.delete(order);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	/**
	 * 查询所有的订单
	 */
	@SuppressWarnings("unchecked")
	public List<Order> findOrderByUserId(Integer userId) {
		Session session = HbnUtils.getSession();
		Query query = session.createQuery("from Order");
		List<Order> orderList = query.list();
		session.close();
		return orderList;
	}

	/**
	 * 
	 */
	public Order findOrderById(Integer id) {
		Session session = HbnUtils.getSession();
		Order order = (Order) session.get(Order.class, id);
		session.close();
		return order;
	}

	/**
	 * 删除所有的订单
	 */
	@Override
	public void deleteAllOrderById(Integer[] orderIds) {
		Session session = HbnUtils.getSession();
		Transaction tx = session.beginTransaction();
		try {
			if (orderIds != null) {
				for (int i = 0; i < orderIds.length; i++) {
					session.delete(session.get(Order.class, orderIds[i]));
				}
			}
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public static void main(String[] args) {
		OrderServiceImpl o = new OrderServiceImpl();
		Integer orderIds[] = new Integer[] { 3, 4 };
		o.deleteAllOrderById(orderIds);
	}
}
